# 模型训练.py  （Python 3 版）
import csv, math, random, joblib, glob

def sigmoid(z):
    return 1.0 / (1.0 + math.exp(-z))

def predict(row, coef):
    z = coef[0] + sum(c*v for c,v in zip(coef[1:], row))
    return 1 if sigmoid(z) >= 0.5 else 0

def train_lr(X, y, epochs=10, lr=0.1):
    coef = [0.0] * (len(X[0]) + 1)
    for epoch in range(epochs):
        for row, label in zip(X, y):
            z = coef[0] + sum(c*v for c,v in zip(coef[1:], row))
            p = sigmoid(z)
            err = label - p
            coef[0] += lr * err
            for i in range(len(row)):
                coef[i+1] += lr * err * row[i]
    return coef

# 读数据
files = glob.glob(r'E:\pythonProject\Xmkb_qg\train_data\*')
X, y = [], []
for f in files:
    for row in csv.reader(open(f, newline=''), delimiter='\t'):
        X.append([float(x) for x in row[1:]])
        y.append(int(row[0]))

print('>>> 样本数', len(X))

# 训练
coef = train_lr(X, y, epochs=10, lr=0.1)
joblib.dump(coef, 'lr_std.model')
print('>>> 标准库 LR 训练完成，模型已保存：lr_std.model')